<template>
  <div class="borrow">
    <!-- 面包屑区域 -->
    <BreadCrumb>借阅历史</BreadCrumb>
    <div class="content">
      <!-- 卡片区域 -->
      <el-card>
        <!-- 搜索与添加区域 row(行)和 col(列) 是栅格布局-->
        <el-row :gutter="20">
          <el-col :span="10">
            <el-input placeholder="Please input" size="large" v-model="input"  class="input-with-select" @keydown.enter="searchBorrow">
              <template #prepend>
                <el-select v-model="select" style="width: 110px">
                  <el-option label="图书编号" value="1" />
                  <el-option label="读者 ID" value="2" />
                </el-select>
              </template>
              <template #append>
                <el-button icon="el-icon-search" @click="searchBorrow"/>
              </template>
            </el-input>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" :icon="BellFilled" @click="clearBorrow">清空借阅历史</el-button>
          </el-col>

        </el-row>
        <!-- 借阅历史列表区域 -->
        <el-table :data="data" border stripe>
          <el-table-column type="index" label="#" align="center"></el-table-column>
          <el-table-column prop="id" label="借阅 ID" align="center" width="80px"/>
          <el-table-column prop="book_id" label="图书 ID" align="center" width="140px" />
          <el-table-column prop="reader_id" label="读者 ID" align="center" width="80px"/>
          <el-table-column prop="borrow_date" label="借阅时间" align="center" width="260px"/>
          <el-table-column prop="back_date" label="归还时间" align="center" width="260px"/>
          <el-table-column prop="if_back" label="是否归还" align="center" width="100px"/>
          <el-table-column label="操作" align="center">
            <!-- 作用域插槽，scope.row 可以拿到对应这一行的数据 -->
            <template #default="scope">
                <el-button type="primary" size="default" :icon="Tickets" @click="showDetail(scope.row)">详情</el-button>
                <el-popconfirm
                confirm-button-text="确认"
                cancel-button-text="取消"
                :icon="InfoFilled"
                icon-color="red"
                title="确认删除该条借阅记录吗?"
                @confirm="delBorrow(scope.row)"
              >
                <template #reference>
                  <el-button type="danger" size="default" :icon="Delete" >删除</el-button>
                </template>
              </el-popconfirm>
            </template>
        </el-table-column>
        </el-table>
      </el-card>
    </div>
  </div>

  <!-- 借阅详情对话框 -->
  <el-dialog v-model="detailDialogVisible" title="借阅详情" width="30%" >
    <div class="info">
    <el-row>借阅读者：{{ detailInfo.reader_name }}</el-row>
    <el-row>借阅图书：{{ detailInfo.book_name }} </el-row>
    <el-row>借阅时间：{{ detailInfo.borrow_date }}</el-row>
    <el-row>归还时间：{{ detailInfo.back_date }}</el-row>
    <el-row>
      <el-col>
        借阅状态：{{ detailInfo.if_back=='is' ? '已归还' : '未归还' }}&nbsp;&nbsp;
        <span class="back" @click="gotoBack" v-if="detailInfo.if_back=='no'">前往归还 <el-icon><promotion /></el-icon> </span>
      </el-col>
    </el-row>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary"  @click="detailDialogVisible = false" >确定</el-button >
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import BreadCrumb from '@/components/common/BreadCrumb.vue'
import { ElMessageBox } from 'element-plus'
import { Delete, BellFilled, Tickets,InfoFilled, Promotion } from '@element-plus/icons-vue'
import { getAllBorrows, getBorrowsByBookId, getBorrowsByReaderId, deleteBorrowById,clearBorrows
} from '@/network/borrow.js'
import { getReaderById } from '@/network/reader.js'
import { getBookById } from '@/network/book.js'
import { onMounted, reactive, ref } from 'vue';
import { messageApi } from '../api/global';
import { useRouter } from 'vue-router'

//* 变量声明
const router = useRouter()
let data = ref([]) // 借阅信息数据
const select = ref('1')  // 下拉选择
const input = ref('') // 文本输入框值 -- 
const detailDialogVisible = ref(false)
// 借阅详细信息
let detailInfo = reactive({
  reader_name: '',
  book_name: '',
  borrow_date: '',
  back_date: '',
  if_back: ''
})
// 将图书信息存到本地，方便图书借阅界面读取
let book = reactive({})

//* 事件处理

// 获取所有借阅记录信息
const getBorrows = async () => {
  const { data: res} = await getAllBorrows()
  data.value = res.data
}

// 查询借阅记录
const searchBorrow = async () => {
  // 图书编号查询
  if (select.value === "1") {
    if (input.value === '' )  return getBorrows()
    const {data:res} = await getBorrowsByBookId(input.value)
    if (res.code !== 200) return messageApi('error', '查询失败！')
    data.value = res.data
  }
  // 读者编号
  if (select.value === "2") {
    if (input.value === '' )  return getBorrows()
    const flag = Number.isInteger(Number(input.value))
    if (!flag) return messageApi('warning', '请输入数字！')
    const {data:res} = await getBorrowsByReaderId(input.value)
    if (res.code !== 200) return messageApi('error', '查询失败！')
    data.value = res.data
  } 
}

// 删除借阅记录
const delBorrow = async (row) => {
  if (row.if_back === 'no') return messageApi('warning', '请先归还该图书，再删除借阅记录！')
  const {data: res} = await deleteBorrowById(row.id);
  if (res.code !== 200) return messageApi('error', '删除借阅记录失败！')
  messageApi('success', res.msg)
  getBorrows()
}

// 清空借阅记录
const clearBorrow = async () => {
  try{
    await ElMessageBox.confirm( `确认清空借阅历史记录吗？`, '警告，执行此操作将不能恢复！', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
    // 先判断借阅历史中，是否存在未归还的图书
    const result = data.value.every(item => item.if_back === 'is')
    if (!result) return messageApi('warning', '清空失败，借阅历史中还存在未归还的图书！')
    // 发起清空借阅记录的请求
    const {data: res} = await clearBorrows();
    if (res.code !== 200) return messageApi('error', '删除借阅记录失败！')
    messageApi('success', res.msg)
    getBorrows()
  }catch(e) {
    messageApi('info', '已取消')
  }
}

// 展示借阅记录的详细信息
const showDetail = async (row) => {
  detailInfo.borrow_date = new Date(row.borrow_date).toLocaleDateString()
  detailInfo.back_date = new Date(row.back_date).toLocaleDateString()
  detailInfo.if_back = row.if_back
  const {data: readerRes} = await getReaderById(row.reader_id)
  detailInfo.reader_name = readerRes.data.readername
  const {data: bookRes} = await getBookById(row.book_id)
  detailInfo.book_name = bookRes.data.bookname
  book = bookRes.data
  detailDialogVisible.value = true

}

// 前往还书界面
const gotoBack = () => {
  router.push({
    path: '/home/backbooks/' + book.id,
    // 添加query参数，还书界面加载完成后可以自动通过这个读者姓名去查询读者信息
    query: {
      readername: detailInfo.reader_name
    }
  })
}
onMounted(() => {
  getBorrows()
})

</script>

<style lang="less" scoped>
.borrow {
  height: 100%;
  width: 85%;
  background-color: #eaedf1;

}
.content {
  width: 100%;
  // height: 600px;
  margin: 0 15px;
  background: #fff;
  overflow: auto;
  width:  1300px;

  .el-card {
    width: 100%;
  }
  .el-table {
    width: 100%
  }
  .el-row {
    margin-bottom: 10px;
    display: flex;
    justify-content: space-between;
  }
}

.input-with-select .el-input-group__prepend {
  background-color: var(--el-fill-color-blank);
}
.info {
  font-size: 16px;
}
a {
  color: blue;
}
.back {
  text-decoration:underline;
  color: blue;
  cursor: pointer;
}

</style>